# -*- coding:utf-8 -*-
import configparser
from common.data import DB
import os

from utils.sendMsg import sendWinMsg

config = configparser.ConfigParser()
INIPATH = os.path.join(DB.ABSPATH, 'config.ini')
INITINI = {"mysql": {"name": 'test', "host": 'localhost', "port": "3306", "user": 'root', "password": 'xl123456'},
           "sqlite": {"name": 'test'},
           "options": {"is_mysql_connect": "False", "mysql_connect_status": "False"},
           "theme": {"palette": "light"},
           "remote": {"remote": "", "is_open_remote": "False"},
           "web": {"browser": "", "webdriver": ""},
           }


def init_ini():
    for sectionIndex, section in enumerate(INITINI):
        config.add_section(section)
        for optionIndex, option in enumerate(INITINI[section]):
            config.set(section, option, INITINI[section][option])
    config.write(open(INIPATH, "w", encoding='utf-8'))


def read_ini(section, option, type=None):
    def _get(section, option, type):
        if type == "int":
            return config.getint(section, option)
        elif type == "bool":
            return config.getboolean(section, option)
        else:
            return config.get(section, option)

    is_read = config.read(INIPATH, encoding='utf-8')
    if is_read:
        if config.has_section(section):
            if config.has_option(section, option):
                return _get(section, option, type)
            sendWinMsg("读取配置", "不存在的option值")
        sendWinMsg("读取配置", "不存在的section值")
    else:
        init_ini()
        return read_ini(section, option, type)


def write_ini(section, option, value):
    is_read = config.read(INIPATH, encoding='utf-8')
    if is_read:
        if config.has_section(section):
            config.set(section, option, value)
        else:
            config.add_section(section)
            config.set(section, option, value)
        config.write(open(INIPATH, "w", encoding='utf-8'))
        sendWinMsg("保存配置", "保存成功")
    else:
        init_ini()
        write_ini(section, option, value)
